<?php
class Controller{

    private $viewname;
    private $controllersname;
    private $layout_path;
    public function render($name = "",$param = []){

        $d = debug_backtrace();
        $this->controllersname = $d[1]['class'];
        $this->viewname = $d[1]['function'];
        $this->layout_path = "view/layout/".$this->controllersname."/layout.html";
        if($name!=""){
            $this->viewname = $name;
            $view_path = "view/".$this->controllersname."/".$this->viewname.".html";
        }
        else
            $view_path = "view/".$this->controllersname."/".$this->viewname.".html";
        $this->process($view_path,$param);
    }
    private function process($view_path,$param){
        $arr = require_once "lib/label/config.php";
        if(!$view = file_get_contents($view_path))
            exit($this->controllersname."控制器没有".$this->viewname."模板");
        if(empty($param['title']))
            $param['title']="自定义MVC";
        extract($param);
        $layout = file_get_contents($this->layout_path);
        $layout = preg_replace("/\{container\}/",$view,$layout);
        foreach ($arr as $key=>$value) {
            if(preg_match($key,$layout))
                $layout = preg_replace($key,$value,$layout);
        }
        $cache_path = "lib/cache/".sha1($layout).".php";
        if(!file_exists($cache_path)){
            $file = fopen($cache_path, "w");
            fwrite($file, $layout);
            fclose($file);
        }
        require_once $cache_path;
    }
    public function __call($name, $arguments)
    {
        $d = debug_backtrace();
        exit($d[1]['class']." 控制器没有 ".$name." 方法");
    }

}
